<template>
  <div class="form-management-container"
       :class="{ 'vab-fullscreen': table.isFullscreen }">
    <el-row :gutter="15">
      <el-col :span="24">
        <el-card shadow="always" style="background-color: #E9F0F8; margin-bottom: 10px; color: #4f7fc7">
          {{ application.name }}
          <el-tag size="mini" v-for="atype in dict.type.application_type" :key="atype.id" v-if="application.type == atype.value">{{atype.label}}</el-tag>
          <span class="description"> {{ application.description }}</span>
        </el-card>
      </el-col>
      <!--表单分类查询-->
      <el-col :span="5">
        <div>
          <el-input
            v-model.trim="filterText"
            placeholder="请输入关键字"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 10px"
          />
        </div>
        <el-tree
          v-loading="!treeList.length"
          ref="treeRef"
          :data="treeList"
          :props="defaultProps"
          :style="{height: treeHeight}"
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          :highlight-current="true"
          default-expand-all
          @node-click="handleNodeClick"
        >
          <div class="el-tree-node__label custom-tree-node custom-tree-item" slot-scope="{ node, data }">
            <span class="name">{{data.name}}</span>
            <div class="right-btns" @click.stop>
              <svg-icon v-if="data.id === 0" @click="addGroup(node, data)" icon-class="plus"></svg-icon>
              <svg-icon v-if="data.id > 1" @click="editGroup(node, data)" icon-class="edit"></svg-icon>
              <svg-icon v-if="data.id > 1" @click="deleteGroup(node, data)" icon-class="delete"></svg-icon>
            </div>
          </div>
        </el-tree>
      </el-col>
      <el-col
        :span="19"
        class="table-container">
        <!--表单搜索-->
        <el-form
          inline
          size="small"
          :model="search.data"
          ref="queryForm"
          v-show="search.show">
          <el-form-item
            label="表单名称"
            prop="name">
            <el-input
              clearable
              v-model="search.data.name"
              placeholder="请输入表单名称"/>
          </el-form-item>
          <el-form-item
            label="表名"
            prop="tableName">
            <el-input
              v-model="search.data.tableName"
              placeholder="请输入表名"
              clearable/>
          </el-form-item>
          <el-form-item
            v-show="!search.fold"
            label="表单结构"
            prop="type">
            <el-select
              v-model="search.data.type"
              placeholder="请选择表单结构">
              <el-option label="单表" value="0"></el-option>
              <el-option label="树表" value="1"></el-option>
              <el-option label="子主表" value="2"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item v-show="!search.fold" label="创建时间">
            <el-date-picker
              v-model="search.dateRange"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="getList">
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              @click="resetQuery">
              重置
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="text" @click="search.fold = !search.fold">
              <span v-if="search.fold">展开</span>
              <span v-else>收起</span>
              <!--              <i
                              class="arrow-up-s-line"
                              :class="{ 'vab-dropdown-active': search.fold }"
                              icon="arrow-up-s-line"/>-->
            </el-button>
          </el-form-item>
        </el-form>
        <el-form inline>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPerm="['form_add']">
              新增
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-download"
              size="mini"
              :disabled="table.single"
              @click="handleExport"
              v-hasPerm="['form_export']">
              导出
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              icon="el-icon-edit"
              size="mini"
              :disabled="table.single"
              @click="handleUpdate"
              v-hasPerm="['form_edit']"
            >修改
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-button
              plain
              size="mini"
              icon="el-icon-delete"
              :disabled="table.multiple"
              @click="handleDelete"
              v-hasPerm="['form_del']"
            >删除
            </el-button>
          </el-form-item>
          <!--          <el-form-item>-->
          <!--            <el-button-->
          <!--              type="primary"-->
          <!--              :disabled="table.multiple"-->
          <!--              icon="el-icon-download"-->
          <!--              size="mini"-->
          <!--              @click="generateCode"-->
          <!--              v-hasPerm="['form_export']"-->
          <!--            >代码生成-->
          <!--            </el-button>-->
          <!--          </el-form-item>-->
          <el-form-item style="float: right; margin-right: 0;">
            <right-toolbar
              :showSearch.sync="search.show"
              :is-fullscreen.sync="table.isFullscreen"
              @queryTable="getList">
            </right-toolbar>
          </el-form-item>
          <el-form-item style="float: right; margin-right: 20px;">
            <el-pagination
              style="margin: 0;"
              @size-change="getList"
              @current-change="getList"
              :current-page.sync="table.current"
              :page-size="table.size"
              :page-sizes="[10,15, 20]"
              layout="total, sizes, prev, pager, next"
              :total="table.total">
            </el-pagination>
          </el-form-item>
        </el-form>

        <!--表单列表信息-->
        <el-table
          border
          :height="tableHeight"
          v-loading="table.loading"
          :data="table.list"
          @selection-change="tableSelectionChange">
          <el-table-column fixed="left" type="selection" width="55" align="center"/>
          <el-table-column label="主键" width="60" prop="id"/>
          <el-table-column label="表单名称" min-width="260" prop="name"/>
          <el-table-column label="表名" min-width="200" prop="tableName"/>
          <el-table-column label="表单标识" min-width="200">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <span>{{ scope.row.code }}</span>
                <div slot="reference">
                  <span class="text-nowrap">{{ scope.row.code }}</span>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="表单结构" prop="type" :formatter="formatTableValue"/>
          <el-table-column label="自动建表" prop="autoCreate" :formatter="formatTableValue"/>
          <el-table-column label="版本号">
            <template slot-scope="scope">
              <span>{{ scope.row.version }}</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="status" :formatter="formatTableValue"/>
          <el-table-column
            fixed="right"
            width="240"
            label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPerm="['form_edit']"
              >修改
              </el-button>
              <!--              <el-button
                              size="mini"
                              type="text"
                              icon="el-icon-news"
                              @click="handleUpdateField(scope.row)"
                              v-hasPerm="['form_edit']"
                            >字段
                            </el-button>-->
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPerm="['form_del']">
                删除
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-sort"
                @click="handleVersion(scope.row)">
                版本
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!--代码生成-->
    <h5ve-dialog
      title="代码生成"
      :show.sync="build.visible">
      <div style="text-align: right; margin-bottom: 20px;">
        <el-button size="medium" @click="cancelBuild">取 消</el-button>
        <el-button size="medium" type="primary" @click="confirmBuild">
          <!--          <vab-icon style="margin-right: 5px; transform: scale(1.3);" icon="folder-download-line"/>-->
          <span>生 成</span>
        </el-button>
      </div>
      <el-card shadow="never">
        <div slot="header">
          <span>基本信息</span>
        </div>
        <el-form
          size="small"
          :model="build.form"
          :rules="build.rules"
          ref="buildForm"
          label-position="left"
          label-width="110px">
          <el-form-item label="是否生成API" prop="isApi">
            <el-radio-group v-model="build.form.isApi">
              <el-radio label="1">否</el-radio>
              <el-radio label="0">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="生成包路径" prop="basePackage">
            <el-input v-model="build.form.basePackage"></el-input>
          </el-form-item>
          <el-form-item label="生成方式" prop="type">
            <el-radio-group v-model="build.form.type">
              <el-radio label="0">ZIP压缩包</el-radio>
              <el-radio label="1">本地路径</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="Number(build.form.type)"
            label="生成路径" prop="fileUrl">
            <el-input v-model="build.form.fileUrl"></el-input>
          </el-form-item>
        </el-form>
      </el-card>
      <el-table
        border
        :data="build.table"
        style="width: 100%; margin-top: 16px;">
        <el-table-column label="表单名称" align="center" prop="name"/>
        <el-table-column label="表单标识" align="center">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <span>{{ scope.row.code }}</span>
              <div slot="reference">
                <span class="text-nowrap">{{ scope.row.code }}</span>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="表单结构" align="center" prop="type" :formatter="formatTableValue"/>
        <el-table-column
          prop="tableName"
          label="表名">
        </el-table-column>
        <el-table-column
          prop="date"
          label="生成模块"
          width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.moudleName" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </h5ve-dialog>

    <!--表单版本控制-->
    <el-dialog
      append-to-body
      :show-close="false"
      class="fullscreen-dialog"
      :visible.sync="version.visible"
      :fullscreen="true">
      <div style="padding: 16px;">
        <el-page-header
          style="margin-bottom: 10px;"
          @back="version.visible = false"
          content="版本控制"/>
        <el-table
          border
          :data="version.list"
          v-loading="version.loading"
          :height="version.list.length ? 'calc(100vh - 130px)' : '200px'">
          <el-table-column label="主键" width="60" align="center" prop="id"/>
          <el-table-column label="表单名称" align="center" prop="name"/>
          <el-table-column label="表单标识" align="center">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <span>{{ scope.row.code }}</span>
                <div slot="reference">
                  <span class="text-nowrap">{{ scope.row.code }}</span>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="表单结构" align="center" prop="type" :formatter="formatTableValue"/>
          <el-table-column label="表名" align="center" prop="tableName"/>
          <el-table-column label="自动建表" align="center" prop="autoCreate" :formatter="formatTableValue"/>
          <el-table-column label="版本号" align="center" prop="version">
            <template slot-scope="scope">
              <span>{{ scope.row.version }}</span>
            </template>
          </el-table-column>
          <el-table-column label="版本" align="center" prop="isMain">
            <template slot-scope="scope">
              <span style="color: #1890ff;" v-show="Number(scope.row.isMain)">主版本</span>
              <span style="color:#aaa;" v-show="!Number(scope.row.isMain)">非主版本</span>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="status" :formatter="formatTableValue"/>
          <el-table-column
            fixed="right"
            width="270"
            label="操作"
            align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :disabled="Number(scope.row.isMain)"
                type="text"
                icon="el-icon-house"
                @click="setFormMain(scope.row)"
                v-hasPerm="['form_edit']">
                设置为主版本
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPerm="['form_edit']">
                修改
              </el-button>
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPerm="['form_del']">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="version.total"
          :page.sync="version.current"
          :limit.sync="version.size"
          @pagination="getVersionList"
        />
      </div>
    </el-dialog>

    <!--添加/编辑分组-->
    <el-dialog
      :visible.sync="groupDialogVisible"
      title="分 组"
      width="30%"
      class="wrapper"
      @closed="groupDialogClosed"
    >
      <el-form ref="groupForm" :model="groupObj" :rules="groupRules" label-width="80px">
        <el-form-item label="分组名称" prop="name">
          <el-input
            ref="name"
            v-model="groupObj.name"
            size="small"
            maxlength="30"
            placeholder= "请输入分组名称"
            @keyup.enter.native="handleClickSaveGroup"
          />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleClickSaveGroup">确 定</el-button>
        <el-button @click="groupDialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <!--表单设计-->
    <el-dialog
      :close-on-press-escape="false"
      :visible.sync="design.visible"
      :destroy-on-close="true"
      :show-close="false"
      class="fullscreen-dialog"
      :fullscreen="true">
      <div class="form-design-header">
        <ul>
          <li v-for="(item, index) in design.menuList"
              @click="changeCarousel(item)"
              :key="'design.menuList.' + index"
              :class="{'active-carousel':  design.current === index}">
            <label>
              <span>
                <span class="icon" :class="item.icon"></span>
                <span>{{ item.name }}</span>
              </span>
            </label>
            <span
              v-show="(index + 1) !== design.menuList.length"
              class="el-icon-arrow-right">
            </span>
          </li>
        </ul>
        <ul class="center-ul">
          <el-button-group>
            <el-button
              size="small"
              :disabled="design.current === 0"
              @click="changeCarousel('prev')"
              icon="el-icon-arrow-left">
              上一步
            </el-button>
            <el-button
              size="small"
              :disabled="design.current === 4"
              @click="changeCarousel('next')">下一步
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </el-button-group>
        </ul>
        <ul class="right-ul">
          <el-button-group>
            <el-button
              size="small"
              @click="closeFormDesign"
              icon="el-icon-circle-close">
              关闭
            </el-button>
            <el-button
              :loading="design.loading"
              @click="submitFormDesign"
              size="small">提交
              <i class="el-icon-circle-check"></i>
            </el-button>
          </el-button-group>
        </ul>
      </div>
      <el-carousel
        ref="carousel"
        arrow="never"
        :autoplay="false"
        indicator-position="none"
        height="calc(100vh - 45px)"
        @change="design.current = $event">
        <el-carousel-item
          v-for="(plugin, index) in design.menuList"
          :key="'design.menuList.' + index"
          :name="plugin.carousel">
          <component v-if="design.visible" :info="design.info" :ref="plugin.carousel" :is="plugin.carousel"/>
        </el-carousel-item>
      </el-carousel>
    </el-dialog>

    <!--表单设计-->
    <el-dialog
      :title="field.title + '-字段信息配置'"
      append-to-body
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      class="dialog-table-container"
      :visible.sync="field.visible">
      <vxe-table
        border
        :height="500"
        :edit-config="{trigger: 'click', mode: 'cell'}"
        :data="field.data">
        <vxe-column type="seq" width="60"></vxe-column>
        <vxe-column field="columnComment" title="字段描述"></vxe-column>
        <vxe-column field="columnName" title="字段名"></vxe-column>
        <vxe-column field="isImport" title="导入" width="120" :formatter="formatterStatus"></vxe-column>
        <vxe-column field="isRepeat" title="重复项" width="120">
          <template #default="{ row }">
            <el-switch v-model="row.isRepeat" active-value="1" inactive-value="0"></el-switch>
          </template>
        </vxe-column>
      </vxe-table>
      <div slot="footer">
        <el-button @click="field.visible = false">取 消</el-button>
        <el-button type="primary" @click="handleEventField">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  delForm,
  getForm,
  getFormCode,
  getGenTable,
  listByIds,
  listForm,
  localCode,
  menuOrFormExport,
  addForm,
  setMain,
  editForm,
  zipCode,
  exportFormColumn,
  selectColumnsByName,
  updateFieldInfo
} from "@/api/toolkit/form";
import {groupTree, delGroup, addGroup, editGroup} from '@/api/toolkit/groupInfo'
import {
  exportFile,
  formatDateRange
} from "./utils";
import baseInfo from "./base-info";
import formDesign from "./form-design";
import fieldInfo from "./field-info";
import buttonDesign from "./button-design";
import formConfig from "./form-config";
import defaultFrom from "@/views/toolkit/form/defaultFrom";
import designData from "@/views/toolkit/form/design";
import buttonList from "@/views/toolkit/form/buttonList";
import menuList from "@/views/toolkit/form/menuList";
import {getApplication} from "@/api/toolkit/application";

export default {
  name: "FormInfo",
  dicts: ['application_type'],
  components: {
    baseInfo,
    formDesign,
    fieldInfo,
    buttonDesign,
    formConfig
  },
  data() {
    const nameValidator = (rule, val, callback) => {
      if (val) {
        callback()
      } else {
        callback(new Error('请输入分组名称'))
      }
    }
    return {
      // 分组相关
      groupDialogVisible: false,
      groupObj: {name: undefined},
      groupRules: {
        name: [{validator: nameValidator}]
      },
      search: {
        fold: true,
        show: true,
        data: {
          applicationId: null,
          isMain: "1",
          groupId: ""
        },
        dateRange: []
      },
      table: {
        list: [],
        size: 20,
        current: 1,
        total: 0,
        single: true,
        multiple: true,
        loading: false,
        autoCreateOptions: [],
        isFullscreen: false
      },
      filterText: "",
      treeList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      field: {
        title: "",
        data: [],
        visible: false,
      },
      build: {
        table: [],
        form: {
          basePackage: "",
          isApi: "1",
          type: "0",
          fileUrl: ""
        },
        rules: {
          basePackage: [{required: true, message: "请输入包路径", trigger: "blur"}],
          fileUrl: [{required: true, message: "本地路径必填", trigger: "blur"}],
          type: [{required: true, message: "请选择生成方式", trigger: "blur"}],
          isApi: [{required: true, message: "请选择是否生成API", trigger: "blur"}]
        },
        visible: false
      },
      version: {
        code: "",
        list: [],
        total: 0,
        size: 20,
        current: 1,
        loading: false,
        visible: false,
      },
      design: {
        loading: false,
        info: {
          form: {
            id: "",
            applicationId: null,
            appType: '',
            name: "",
            code: "",
            tableName: "",
            databaseName: "master",
            remarks: "",
            menuId: "",
            isComputed: "",
            formType: "",
            groupId: "",
            type: "0",
            treeName: ""
          },
          buttonList: buttonList.data,
          column: [],
          options: {}
        },
        current: 0,
        menuList: menuList.data,
        visible: false,
      },
      model: {
        visible: false,
        moData: []
      },
      script: {
        loading: false,
        visible: false
      },
      application: {
        id: null,
        name: undefined,
        type: undefined,
        industry: undefined,
        cover: undefined,
        version: "1.0.0",
        description: undefined
      }
    }
  },
  computed: {
    tableHeight() {
      let h = 350;
      if (this.table.isFullscreen) h = 150;
      if (!this.search.show) h -= 50;
      return this.table.list.length ? `calc(100vh - ${h}px)` : "150px";
    },
    treeHeight() {
      return this.table.isFullscreen ? "calc(100vh - 90px)" : "calc(100vh - 300px)";
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeRef.filter(val);
    }
  },
  created() {
    const appId = this.$route.params && this.$route.params.appId;
    this.getDicts("application_type").then(response => {
      this.appTypeOptions = response.data;
    });
    if (appId) {
      this.search.data.applicationId = appId;
      this.getTreeList(appId);
      getApplication(appId).then(response => {
        this.application = response.data;
      });
    }
    this.getDictionary();
  },
  methods: {
    /**格式化状态值*/
    formatterStatus(row) {
      if (row.cellValue) {
        return ['否', '是'][row.cellValue]
      }
      return '未填';
    },
    /**新增表单数据*/
    handleAdd() {
      this.design = JSON.parse(JSON.stringify(designData.data));
      getFormCode().then(response => {
        if (response.data) {
          this.design.info.form.code = response.data;
          this.design.info.form.applicationId = this.application.id;
          this.design.visible = true;
        }
      })
    },
    /**导出表单列表数据*/
    handleExport(row) {
      const id = row.id || this.table.ids[0];
      const form = this.table.list.find(item => item.id === id);
      exportFile({
        method: "GET",
        suffix: ".xlsx",
        params: "/" + form.code,
        fileName: form.name,
        download: true,
        url: exportFormColumn()
      })
    },
    /**删除表单数据*/
    handleDelete(row) {
      const isMain = Number(row.isMain);
      const ids = row.id || this.table.ids;
      this.$confirm(isMain ? '当前表单为主版本，删除后将删除所有历史版本！确定删除吗？' : "确定删除吗？", "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delForm(ids);
      }).then(() => {
        this.$notify.success("已删除");
        this.getVersionList();
        this.getList();
      })
    },
    /**更新、修改表单数据*/
    handleUpdate(row) {
      this.design = JSON.parse(JSON.stringify(designData.data));
      const id = row.id || this.table.ids[0];
      this.fullLoading("正在加载表单数据");
      getForm(id).then(response => {
        const {data} = response;
        data.applicationId = this.application.id;
        data.appType = this.application.type;
        Object.assign(this.design.info.form, data);
        const options = JSON.parse(data.data);
        this.design.info.column = options.column;
        this.design.info.column.forEach(item => {
          item.isWatch = true
        })
        this.design.info.options = options;
        if (data.btnData) {
          this.design.info.buttonList = JSON.parse(data.btnData);
        }
        this.design.visible = true;
        this.fullscreenLoading.close();
      }).catch(() => {
        this.fullscreenLoading.close();
      })
    },
    /**更新、修改表单字段数据*/
    handleUpdateField(row) {
      const tableName = "form_" + row.tableName;
      this.fullLoading("正在加载表单数据");
      selectColumnsByName(tableName).then(response => {
        if (response.data) {
          let list = response.data;
          let filterNames = ['id', 'create_by', 'update_by', 'create_time', 'update_time', 'del_flag', 'data_from', 'remarks'];
          this.field.data = list.filter(item => !filterNames.includes(item.columnName));
        }
        this.field.title = row.name;
        this.field.visible = true;
        this.fullscreenLoading.close();
      }).catch(() => {
        this.fullscreenLoading.close();
      })
    },
    handleEventField() {
      let list = this.field.data;
      updateFieldInfo({
        columns: list
      }).then(response => {
        this.$notify.success("操作成功！");
        this.field.visible = false;
      })
    },
    /**关闭表单设计*/
    closeFormDesign() {
      this.$confirm('确定关闭表单设计吗？关闭后不会保留或更改表单设计内容！', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.design.visible = false;
      })
    },
    /**关闭表单设计*/
    closeModelDesign() {
      this.model.visible = false;
    },
    /**保存表单设计*/
    submitFormDesign() {
      this.design.loading = true;
      for (let i = 0; i < this.design.menuList.length; i++) {
        const item = this.design.menuList[i];
        const {carousel, ref, name} = item;
        const plugin = this.$refs[carousel][0];
        if (ref) {
          let validFlag = false;
          plugin.$refs[ref].validate(valid => {
            validFlag = valid;
          })
          if (!validFlag) {
            this.design.loading = false;
            return this.$notify.warning(`【${name}】数据验证不通过`);
          }
        } else if (carousel === "formDesign") {
          const jsonStr = plugin.$refs[carousel].getWidgetFormJson();
          const {column} = JSON.parse(jsonStr);
          this.design.info.column = column;
          if (!column.length) {
            this.design.loading = false;
            return this.$notify.warning(`【${name}】至少选择一个字段`);
          }
          let sum = 0;
          column.forEach(item => {
            sum += item.dataLength ? Number(item.dataLength) : 0;
          })
          if (sum > 8060) {
            this.design.loading = false;
            this.fullscreenLoading.close();
            return this.$notify.error("表单数据长度总和大于8060，当前长度为" + sum);
          }
        }
      }
      const form = defaultFrom;
      form.column = this.design.info.column;
      const params = {
        ...this.design.info.form,
        data: JSON.stringify(form),
        btnData: JSON.stringify(this.design.info.buttonList),
      }
      const $refs = this.$refs.formConfig[0];
      if ($refs.childTable && this.design.info.form.type === '2') {
        let childTable = JSON.parse(JSON.stringify($refs.childTable));
        childTable = childTable.map(map => {
          return {
            foreignKey: map.foreignKey,
            tableName: map.prop,
            tableComment: map.label,
            childType: map.childType || "tempTable"
          }
        })
        params.childTable = JSON.stringify(childTable);
      }
      this.fullLoading("正在保存");
      console.log(params)
      if (params.id) {
        editForm(params).then(response => {
          if (response) {
            this.fullscreenLoading.close();
            this.design.visible = false;
            this.$notify.success("已更新");
            this.getList();
          }
        }).catch(() => {
          this.design.loading = false;
          this.fullscreenLoading.close();
        })
      } else {
        addForm(params).then(response => {
          if (response) {
            this.$notify.success("已保存");
            this.fullscreenLoading.close();
            this.design.visible = false;
            this.$alert('刷新页面即可开始体验', '提示', {
              confirmButtonText: '知道了'
            });
            this.getList();
          }
        }).catch(() => {
          this.design.loading = false;
          this.fullscreenLoading.close();
        })
      }
    },
    /**改变表单设计步骤*/
    changeCarousel(data) {
      const index = this.design.current;
      const {carousel, ref, name} = this.design.menuList[index];
      const plugin = this.$refs[carousel][0];
      if (ref) {
        let validFlag = false;
        plugin.$refs[ref].validate(valid => {
          validFlag = valid;
        })
        if (!validFlag) {
          return this.$notify.warning(`【${name}】数据验证不通过`);
        }
      } else if (carousel === "formDesign") {
        const jsonStr = plugin.$refs[carousel].getWidgetFormJson();
        const {column} = JSON.parse(jsonStr);
        this.design.info.column = column;
        if (!column.length) {
          return this.$notify.warning(`【${name}】至少选择一个字段`);
        }
      }
      if (data === 'prev') {
        this.$refs.carousel.prev();
      } else if (data === 'next') {
        this.$refs.carousel.next();
      } else if (data.carousel) {
        this.$refs.carousel.setActiveItem(data.carousel);
      }
    },
    /**查看表单历史版本*/
    handleVersion(data) {
      this.version.code = data.code;
      this.version.visible = true;
      this.getVersionList();
    },
    /**设置主版本*/
    setFormMain(data) {
      const row = JSON.parse(JSON.stringify(data));
      setMain(row).then(response => {
        if (response) {
          this.getVersionList();
          this.getList();
          this.$notify.success("设置成功");
        }
      })
    },
    /**获取表单版本列表*/
    getVersionList() {
      this.version.loading = true;
      listForm({
        size: this.version.size,
        code: this.version.code,
        current: this.version.current
      }).then(response => {
        const {data, total} = response;
        this.version.list = data;
        this.version.total = total;
        this.version.loading = false;
      });
    },
    /**表格选择触发*/
    tableSelectionChange(selection) {
      this.table.ids = selection.map(item => item.id);
      this.model.moData = selection.map(item => ({
        ...item,
        value: item.id,
        label: item.name,
        tableName: item.tableName
      }));
      this.table.single = selection.length !== 1;
      this.table.multiple = !selection.length;
    },
    /**代码生成*/
    generateCode() {
      this.fullLoading();
      listByIds(this.table.ids).then(response => {
        this.build.table = response.data;
        getGenTable({tableName: "", tableComment: ""}).then(response => {
          if (response.data) {
            const {genPath, packageName} = response.data;
            this.build.form.basePackage = packageName;
            this.build.form.fileUrl = genPath;
            this.build.visible = true;
            this.fullscreenLoading.close();
          }
        })
      })
    },
    /**取消生成代码*/
    cancelBuild() {
      this.resetForm("buildForm");
      this.build.visible = false;
    },
    /**确定生成代码*/
    confirmBuild() {
      this.$refs['buildForm'].validate(valid => {
        if (valid) {
          let tables = [];
          let moduleName = [];
          this.build.table.forEach(item => {
            tables.push(item.tableName);
            moduleName.push(item.moudleName);
          })
          this.build.form.tables = tables.join(",");
          this.build.form.moudleName = moduleName.join(",");
          exportFile({
            method: "POST",
            suffix: ".zip",
            params: this.build.form,
            fileName: "代码",
            download: !Number(this.build.form.type),
            url: Number(this.build.form.type) ? localCode() : zipCode()
          }, () => {
            this.cancelBuild();
            this.$notify.success("已生成");
          })
        } else {
          return this.$notify.warning("表单校验不通过");
        }
      })
    },
    /**获取表单信息列表数据*/
    getList() {
      this.table.loading = true;
      const date = formatDateRange(this.search.dateRange);
      const page = {size: this.table.size, current: this.table.current};
      listForm({...date, ...this.search.data, ...page}).then(response => {
        const {data, total} = response;
        this.$set(this.table, "list", data);
        this.table.total = total;
        this.table.loading = false;
      });
    },
    /**触发表单关联的树形列表*/
    handleNodeClick(data) {
      this.search.data.groupId = data.id;
      this.tempFormType = data;
      this.getList();
    },
    /**格式化表格数据*/
    formatTableValue(row, column) {
      if (column.property === 'type') {
        switch (row.type) {
          case "0":
            return "单表";
          case "1":
            return "树表";
          case "2":
            return "子主表"
        }
      } else if (column.property === 'autoCreate') {
        const {autoCreate} = row;
        return this.selectDictLabel(this.table.autoCreateOptions, autoCreate);
      } else if (column.property === 'status') {
        return this.selectDictLabel(this.table.statusOptions, row.status);
      }
    },
    /**获取相关字典数据*/
    getDictionary() {
      let p1 = new Promise(resolve => {
        this.getDicts("yes_no").then(response => {
          this.table.autoCreateOptions = response.data;
          resolve(response)
        })
      })
      let p2 = new Promise(resolve => {
        this.getDicts("status").then(response => {
          this.table.statusOptions = response.data;
          resolve(response)
        })
      })
      Promise.all([p1, p2]).then(() => {
        this.getList();
      })
    },
    /**获取全部表单菜单树形结构*/
    getTreeList(appId) {
      groupTree({applicationId: appId}).then(response => {
        this.treeList = response.data;
      })
    },
    /**树形列表节点过滤*/
    filterNode(value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
    /**重置查询条件*/
    resetQuery() {
      this.resetForm("queryForm");
      this.search.data.groupId = "";
      this.getList();
    },
    /**全屏加载*/
    fullLoading(text) {
      this.fullscreenLoading = this.$loading({
        lock: true,
        text: text || '正在初始化数据',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
// 添加分组
    addGroup(node, data) {
      this.groupObj = {
        name: undefined,
        type: '0',
        parentId: data.id
      }
      this.groupDialogVisible = true
    },
    // 编辑分组
    editGroup(node, data) {
      this.groupObj = JSON.parse(JSON.stringify(data))
      this.groupDialogVisible = true
    },
    // 删除分组
    deleteGroup(node, data) {
      this.$confirm(`确认要删除分组："${data.name}"吗?`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delGroup(data.id)
      }).then(() => {
        this.getGroupTree()
        this.msgSuccess('删除成功')
      }).catch(function () {
      })
    },
    groupDialogClosed() {
      this.groupObj = {name: undefined}
    },
    handleClickSaveGroup() {
      this.$refs['groupForm'].validate(valid => {
        if (valid) {
          const fun = this.groupObj.id ? editGroup : addGroup
          fun(this.groupObj)
            .then(_ => {
              this.getGroupTree()
              this.$message({
                message: '保存成功',
                type: 'success',
                showClose: true
              })
              this.groupDialogVisible = false
            })
            .catch(_ => {
            })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>

.form-management-container {
  padding: 15px;
  background-color: #FFFFFF;

  .custom-tree-item {
    &:after {
      content: "";
      display: block;
      clear: both;
    }

    &:hover {
      .right-btns {
        opacity: 1;
      }
    }

    font-size: 16px;
    width: 100%;

    .right-btns {
      float: right;
      color: #000;
      opacity: 0;
      transition: .3s all;
      user-select: none;

      .svg-icon {
        margin: 0 2px;

        &:hover {
          color: #999;
        }
      }
    }
  }

  .description{
    font-size: 14px;
    color: #cccccc;
  }

  .text-nowrap {
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .form-design-header {
    position: relative;
    height: 45px;
    border-bottom: 1px solid #f0f0f0;

    ul {
      margin: 0;

      li {
        line-height: 45px;
        list-style: none;
        float: left;

        .el-icon-arrow-right {
          padding: 0 16px;
          font-weight: 700;
        }

        .icon {
          padding-right: 5px;
        }

        &:hover {
          font-weight: 700;
          transition: .3s;
          color: #409eff;
        }
      }

      .active-carousel {
        color: #409eff;
      }
    }

    .center-ul {
      position: absolute;
      left: 50%;
      top: 6px;
    }

    .right-ul {
      position: absolute;
      top: 6px;
      right: 20px;
    }
  }
}

::v-deep .el-card__body {
  padding: 10px;
}
</style>
<style>

.fullscreen-dialog .el-dialog__header {
  display: none;
}

.fullscreen-dialog .el-dialog__body {
  padding: 0 !important;
  margin: 0;
}

.dialog-table-container *::-webkit-scrollbar {
  width: 15px !important;
  height: 15px !important;
}

.dialog-table-container *::-webkit-scrollbar-thumb {
  background-color: #d4d5d6 !important;
  border-radius: 2px !important;
}
</style>
